/**
 * Notes: 门禁控制模块业务逻辑 - 宠物门店预约小程序
 * Date: 2025-01-27 
 */

const BaseService = require('./base_service.js');
const AppointmentModel = require('../model/appointment_model.js');
const StoreModel = require('../model/store_model.js');
const DeviceService = require('./device_service.js');
const timeUtil = require('../../framework/utils/time_util.js');

class AccessService extends BaseService {

	/**
	 * 请求扫码开门
	 * @param {string} userId 用户ID
	 * @param {string} storeId 门店ID
	 * @param {string} topic MQTT主题
	 * @returns {Object} 开门结果
	 */
	async requestOpenDoor(userId, storeId, topic) {
		// 验证参数
		if (!storeId) {
			throw new Error('门店ID不能为空');
		}
		if (!topic) {
			throw new Error('MQTT主题不能为空');
		}

		// 查询门店信息
		const store = await StoreModel.getOne({ _id: storeId });
		if (!store) {
			throw new Error('门店不存在');
		}

		// 记录开门日志
		await this.logAccess(userId, storeId, null, 'success');

		// 调用统一的MQTT控制方法
		await this.triggerDoorOpen(topic);

		return {
			success: true,
			message: '开门指令已发送，门将在10秒后自动关闭',
			storeName: store.name
		};
	}

	/**
	 * 检查用户是否有有效预约
	 * @param {string} userId 用户ID
	 * @param {string} storeId 门店ID
	 * @returns {Object|null} 有效预约信息
	 */
	async checkValidAppointment(userId, storeId) {
		const now = timeUtil.time();
		const todayStart = this.getTodayStart();
		const todayEnd = this.getTodayEnd();

		// 查找今天的有效预约
		let where = {
			userId: userId,
			storeId: storeId,
			status: { $in: [AppointmentModel.STATUS.PAID, AppointmentModel.STATUS.IN_SERVICE] },
			appointmentTime: { $gte: todayStart, $lte: todayEnd }
		};

		const appointment = await AppointmentModel.getOne(where);
		return appointment;
	}

	/**
	 * 记录门禁访问日志
	 * @param {string} userId 用户ID
	 * @param {string} storeId 门店ID
	 * @param {string} appointmentId 预约ID
	 * @param {string} status 访问状态
	 */
	async logAccess(userId, storeId, appointmentId, status) {
		// 这里应该记录到access_logs表
		// 暂时只打印日志
		console.log('门禁访问日志:', {
			userId,
			storeId,
			appointmentId,
			status,
			time: timeUtil.time()
		});
	}

	/**
	 * 触发门锁开门
	 * @param {string} topic MQTT主题
	 */
	async triggerDoorOpen(topic) {
		try {
			const deviceService = new DeviceService();

			console.log('发送MQTT开门指令，主题:', topic);
			
			// 使用统一的sendMqttCommand方法发送开门指令
			const openResult = await deviceService.sendMqttCommand(topic, 'on', 0);

			if (!openResult.success) {
				throw new Error('开门指令发送失败: ' + openResult.message);
			}

			console.log('门锁开门指令发送成功，10秒后将自动关闭');
			
			// 设置10秒后自动关门
			setTimeout(async () => {
				try {
					console.log('发送MQTT关门指令，主题:', topic);
					
					const closeResult = await deviceService.sendMqttCommand(topic, 'off', 0);

					if (closeResult.success) {
						console.log('门锁自动关闭指令发送成功');
					} else {
						console.error('门锁自动关闭指令发送失败:', closeResult.message);
					}
				} catch (error) {
					console.error('门锁自动关闭时发生错误:', error);
				}
			}, 10000); // 10秒后执行

			return true;
		} catch (error) {
			console.error('门锁开门操作失败:', error);
			throw error;
		}
	}

	/**
	 * 获取今天开始时间戳
	 * @returns {number} 时间戳
	 */
	getTodayStart() {
		const now = new Date();
		const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		return Math.floor(today.getTime() / 1000);
	}

	/**
	 * 获取今天结束时间戳
	 * @returns {number} 时间戳
	 */
	getTodayEnd() {
		const todayStart = this.getTodayStart();
		return todayStart + 24 * 60 * 60 - 1; // 23:59:59
	}
}

module.exports = AccessService;
